<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作者" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程搜索关键字" prop="coursePrimary">
        <el-input
          v-model="queryParams.coursePrimary"
          placeholder="请输入课程搜索关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['siyun-course:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['siyun-course:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程主键" align="center" prop="id" />
      <el-table-column label="作者" align="center" prop="username" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程简介" align="center" prop="courseIntro" >
        <template slot-scope="scope">
          <span v-html="scope.row.courseIntro"></span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" >
        <template slot-scope="scope">
          <span v-html="scope.row.remarks"></span>
        </template>
      </el-table-column>
      <el-table-column label="缩略图" align="center" prop="thum" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.thum" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="courseCstatus">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            v-if="scope.row.courseCstatus === 2"
          >已审核</el-button>
          <div v-if="scope.row.courseCstatus === 5">
            <el-button
            size="mini"
            type="danger"
            >未过审</el-button>
          </div>
          <div v-if="scope.row.courseCstatus === 3">
            <el-button
              size="mini"
              type="primary"
              @click="handleChangeStatus(scope.row, 2)"
            >通过</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleChangeStatus2(scope.row, 5)"
            >不通过</el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['siyun:course:list']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['siyun:course:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 查看 -->
    <el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
        <el-descriptions class="margin-top" :column="3" :size="size" border>
          <!-- Top Section -->
          <el-descriptions-item label="作者">{{ form.username }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ form.courseName }}</el-descriptions-item>
          <el-descriptions-item label="课程视频"><el-button @click="imgUrlss">点击观看</el-button></el-descriptions-item>
          <el-descriptions-item label="缩略图">
            <image-preview :src="form.thum" :width="200" :height="200"/>
          </el-descriptions-item>
          <el-descriptions-item label="课程简介">{{ form.courseIntro }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ form.remarks }}</el-descriptions-item>
          <el-descriptions-item label="课程原价">{{ form.coursePrice }}</el-descriptions-item>
          <el-descriptions-item label="课程现价">{{ form.courseNprice }}</el-descriptions-item>
          <el-descriptions-item label="课程搜索关键字">
            <el-tag v-for="tag in form.coursePrimary" :key="tag" style="margin-right: 5px;">{{ tag }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <br />
        <el-descriptions class="margin-top" :column="2" :size="size" border>
          <!-- Middle Section -->
          <el-descriptions-item label="点赞数量">{{ form.likeNum }}</el-descriptions-item>
          <el-descriptions-item label="分享数量">{{ form.shareNum }}</el-descriptions-item>
          <el-descriptions-item label="收藏数量">{{ form.collectNum }}</el-descriptions-item>
          <el-descriptions-item label="预览数量">{{ form.lookNum }}</el-descriptions-item>
          <el-descriptions-item label="销售数量">{{ form.saleNum }}</el-descriptions-item>
        </el-descriptions>
        <br />
        <!-- Bottom Section -->
        <el-descriptions class="margin-top" :column="2" :size="size" border>
          <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
          <el-descriptions-item label="修改人">{{ form.updateBy }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ form.updateTime }}</el-descriptions-item>
        </el-descriptions>
        <div slot="footer" class="dialog-footer">
          <el-button @click="viewClose">关 闭</el-button>
        </div>
      </el-dialog>
    <!-- 反馈页面 -->
    <el-dialog :title="feedbackTitle" :visible.sync="feedbackOpen" width="500px" append-to-body>
      <el-form ref="feedbackForm" :model="feedbackForm" :rules="feedbackRules" label-width="80px">
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="feedbackForm.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFeedback">取 消</el-button>
        <el-button type="primary" @click="submitFeedback">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { getCourse, delCourse, addCourse, updateCourse, listCourse } from "@/api/siyun/course";
import { listFeedback, addFeedback } from "@/api/siyun/feedback";
import { getUserProfile } from "@/api/system/user"

export default {
  name: "Course",
  data() {
    return {
      feedbackOpen: false, // 控制反馈对话框的显示与隐藏
      feedbackTitle: "", // 反馈对话框标题
      feedbackForm: {
        projectId: null,
        itemId: null,
        state: null,
        remarks: null,
        userId: null
      },
      feedbackRules: {
              // 规则就是用来打破的
      },
      size: 'medium', // 添加 size 属性并设置默认值
      viewOpen: false, // 控制查看对话框的显示与隐藏
      // 关键字
      options: [{
          value: '选项1',
          label: 'JAVA'
        }, {
          value: '选项2',
          label: 'MYSQL'
        }, {
          value: '选项3',
          label: 'C++'
        }, {
          value: '选项4',
          label: 'C语言'
        }, {
          value: '选项5',
          label: '素质教育'
      }],
      value1: [],
      aaa: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为查看模式
      isViewing: false,
      userProfile: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        courseName: null,
        coursePrimary: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        coursePrice: [
          { required: true, message: "课程原价不能为空", trigger: "blur" }
        ],
        courseNprice: [
          { required: true, message: "课程现价不能为空", trigger: "blur" }
        ]
      },
      // 自动完成建议列表
      restaurants: [],
    };
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    // 视频观看
    imgUrlss(){
      this.$store.commit('shipin/SET_VIDEOCOURSEID',this.form.id);
      //跳转视频列表页面
      this.$router.push({ path: '/course/coures/video' });
    },
    handleChangeStatus(row, newStatus) {
      this.reset();
      updateCourse({ id: row.id, courseCstatus: newStatus })
        .then(response => {
          this.$message.success("状态更新成功");
          this.getList(); // 刷新列表以反映最新状态
        })
        .catch(error => {
          this.$message.error("状态更新失败");
        });
    },
    handleChangeStatus2(row, newStatus) {
      this.reset();
      this.feedbackOpen = true;
      this.feedbackForm.itemId = row.id; // 设置 itemId 为当前行的 id
      updateCourse({ id: row.id, courseCstatus: newStatus })
        .then(response => {
          this.$message.success("状态更新成功");
          this.getList(); // 刷新列表以反映最新状态
        })
        .catch(error => {
          this.$message.error("状态更新失败");
        });
    },
    submitFeedback() {
      this.$refs["feedbackForm"].validate(valid => {
        if (valid) {
          this.feedbackForm.projectId = 1;
          this.feedbackForm.state = 1;
          this.feedbackForm.userId = this.userProfile.userId
          this.feedbackForm.time = this.getCurrentTime();
          addFeedback(this.feedbackForm).then(response => {
            this.$message.success("反馈提交成功");
            this.feedbackOpen = false;
            this.getList(); // 刷新列表以反映最新状态
          }).catch(error => {
            this.$message.error("反馈提交失败");
          });
        }
      });
    },
    getCurrentTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    cancelFeedback() {
      this.resetFeedbackForm();
      this.feedbackOpen = false;
    },
    resetFeedbackForm() {
      this.feedbackForm = {
        projectId: null,
        itemId: null,
        state: null,
        remarks: null,
        userId: null
      };
    },
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleAutocompleteSelect(item) {
    },
    mounted() {
      this.restaurants = this.loadAll();
    },
    formatcourseStatus(row) {
      const statusMap = {
        2: '上架',
        3: '未上架'
      };
      return statusMap[row.courseStatus] || '未知';
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUser() {
      getUserProfile().then(response => {
        this.userProfile = response.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.isViewing = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加课程";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.id || this.ids[0];
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "修改课程";
        this.open = true;
      });
    },
    // 查看按钮操作
    handleView(row) {
      this.reset();
      const courseId = row.id;
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "查看课程";
        this.viewOpen = true; // 打开查看对话框
      });
    },
    // 关闭查看窗口
    viewClose() {
      this.viewOpen = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.id || this.ids;
      this.$confirm('是否确认删除课程编号为"' + courseIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCourse(courseIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
